package com.hx0311.core.dao.support;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResultSetUtil {

	/**
	 * 把结果集中的数据封装到Map中
	 * 
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public static Map toMap(ResultSet rs, ResultSetMetaData meta) throws SQLException {
		if (rs != null && meta != null) {
			Map data = new HashMap();
			for (int i = 1; i <= meta.getColumnCount(); i++) {
				data.put(meta.getColumnLabel(i).toUpperCase(), rs.getObject(i));
			}
			return data;
		}
		return Collections.EMPTY_MAP;
	}
	
	public static Object toObject(Object o, ResultSet rs) throws SQLException{
		copyMapValues(o, toMap(rs, rs.getMetaData()));
		return o;
	}

	/**
	 * 从Map中复制数据到指定对象
	 * 
	 * @param object
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	public static void copyMapValues(Object object, Map data) {
		if (object != null) {
			Method[] methods = object.getClass().getMethods();
			String methodName = null;
			String proName = null;
			for (Method method : methods) {
				methodName = method.getName();
				if (methodName.startsWith("set")) {
					proName = methodName.substring("set".length());
					try {
						method.invoke(object, data.get(proName.toUpperCase()));
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static List toList(ResultSet rs) throws SQLException {
		if (rs != null) {
			List datas = new ArrayList();
			ResultSetMetaData meta = rs.getMetaData();
			while (rs.next()) {
				datas.add(toMap(rs, meta));
			}
			return datas;
		}
		return java.util.Collections.EMPTY_LIST;
	}
}
